$(document).ready(function() {
	// Attach all forms with protection against non-HTML5 compliant browsers:
	$('form').each(function(){
		$(this).submit(function(e) { 
			validateRequiredInputs(e);
		});
	});
});

/**
 * Poor man's version of what jquery-validation-ui plugin since it is buggy.
 * 
 * @param e The submit event to stop.
 */
function validateRequiredInputs(e) {
	var errorClass = 'error'; // assumes main.css is included
	var errorFound = false;
	
	// Validate all fields instead of stopping at first invalid one:
	$('[required=""]').each(function() {
		var parent = $(this).parent();
		
		// Determine checked state if checkable:
		var type = $(this).attr('type');
		var isCheckable = type == 'checkbox' || type == 'radio';
		var checkedValue;
		if (isCheckable) {
			var selector = 'input[name="' + $(this).attr('name') + '"]:checked';
			checkedValue = $(selector).val();
		}
		
    	// Update input UI via css of parent, if necessary:
	    if ($(this).val() == '' || (isCheckable && !checkedValue)) {
	    	if (!parent.hasClass(errorClass)) {
	    		parent.addClass(errorClass);
	    	}
	    	// Set flag for return value:
	    	if (!errorFound) {
	    		errorFound = true;
	    	}
	    }
	    else if (parent.hasClass(errorClass)) {
	    	parent.removeClass(errorClass);
	    }
	});
	
	// Should only have errors if browser is non-HTML5 compliant (IE < 10, Opera):
	if (errorFound) {
		alert('Please fill in all required fields.');
		
		// Cancel the submit:
		e.preventDefault();
	}
}